<?php
// +----------------------------------------------------------------------
// | ManniuRead
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://manniuyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: heitao <read@manniuyun.com>
// +----------------------------------------------------------------------

namespace app\book\controller\member;

use app\book\base\BookMemberBase;

use think\Cache;
use app\book\model\Book as BookModel;
use app\book\model\Chapter as ChapterModel;
use app\book\model\BookBookcases as BookBookcasesModel;
use app\book\model\BookAutoSubscription;

class Book extends BookMemberBase{
	/**
     * 书架
     * @access public
     * @return \think\Response
     */
    public function bookcase(){
        $bookcases = BookBookcasesModel::all(['uid'=>$this->uid]);
        $list = [];

        $book_model = new BookModel;
        $chapter_model = new ChapterModel;
        if($bookcases){
            foreach ($bookcases as $bookcase) {
                $list[$bookcase->book_id] = $book_model->getBook($bookcase->book_id);
                $chapters = $chapter_model->getChapterList($bookcase->book_id);
                $list[$bookcase->book_id]['last_chapter'] = !empty($chapters) ? end($chapters) : null;
                $list[$bookcase->book_id]['last_read_chapter'] = isset($chapters[(int)$bookcase->lrc_id]) ? $chapters[(int)$bookcase->lrc_id] : null;
            }
        }

        $this->assign([
            'list' => $list
        ]);
        return $this->getTemplate();
    }

    /**
     * 自动订阅列表
     * @access public
     * @return \think\Response
     */
    public function autoSubscriptionList(BookAutoSubscription $bas){
        $uid = $this->uid;
        $list = [];
        $auto_subscription_books = $bas->getBooks($this->uid);
        if($auto_subscription_books && $auto_subscription_books !== 'N'){
            $BookModel = new BookModel;
            foreach ($auto_subscription_books as $book_id) {
                $list[$book_id] = $BookModel->getBook($book_id);
            }
        }
        $this->assign([
            'list' => $list
        ]);
        return $this->getTemplate();
    }

    /**
     * 加入书架
     * @access public
     * @param int $bid 图书id
     * @return mixed
     */
    public function addBookcase($bid = 0){
    	$error = $success = [];
        $error['status'] = 0;
    	$bid = (int)$bid;
    	if(!$bid){
    		$error['msg'] = '缺少图书id，请刷新后重试！';
    	}
        $bookcases_cache = Cache::get('bookcases_uid_'.$this->uid);
        // 查询书架缓存中是否存在此书
        if(isset($bookcases_cache[$bid])){
            $error['msg'] = '图书已在书架，无需重复添加哦！';
        }else{
            if(!BookModel::where('id',$bid)->count()){
                $error['msg'] = '图书不存在或已被删除，请刷新后重试！';
            }else if(BookBookcasesModel::where(['uid'=>$this->uid,'book_id'=>$bid])->count()){
                $error['msg'] = '图书已在书架，无需重复添加哦！';
            }else{
                BookBookcasesModel::create([
                    'uid'        => $this->uid,
                    'book_id'    => $bid
                ]);
                $success['status']   = 1;
                $success['msg']      = '图书已成功加入书架！';
            }
            // 更新此用户的书架缓存
            BookBookcasesModel::updateBookcaseCacheByUid($this->uid);
        }
    	return json(isset($success['status']) ? $success : $error);
    }

    /**
     * 删除书架
     * @access public
     * @param int $bid 图书id
     * @return mixed
     */
    public function removeBookcase($bid = 0){
        $bid = (int)$bid;
        if(!$bid){
            $this->error('缺少图书id，请刷新后重试！');
        }
        $bookcase = BookBookcasesModel::get(['uid'=>$this->uid,'book_id'=>$bid]);
        if($bookcase){
            $bookcase->delete();
            // 更新此用户的书架缓存
            BookBookcasesModel::updateBookcaseCacheByUid($this->uid);
            $this->redirect('book/member.book/bookcase');
        }else{
            $this->error('图书不存在或已被删除，请刷新后重试！');
        }
    }

    /**
     * 自动订阅
     * @access public
     * @param int $bid 图书id
     * @param int $switch 自动订阅标识，1：开启，0：关闭
     * @return mixed
     */
    public function autoSubscription($bid = 0, $switch = 0, BookAutoSubscription $bas){
        $bid = (int)$bid;
        $switch = (int)$switch;
        $status = 0;
        $msg = '';
        if(($switch !== 0 && $switch !== 1) || !$bid){
            $msg = '自动订阅参数错误！';
        }else if(!BookModel::where('id',$bid)->count()){
            $msg = '图书不存在或已被删除，请刷新后重试！';
        }else{
            $auto_subscription_books = $bas->getBooks($this->uid);
            if($switch){
                // N代表null,表示最新缓存为空
                if($auto_subscription_books !== 'N' && is_array($auto_subscription_books) && in_array($bid, $auto_subscription_books)){
                    $msg = '本书已开启自动订阅，请勿重复设置！';
                }else{
                    $auto_subscription_book = BookAutoSubscription::get(['uid'=>$this->uid, 'book_id'=>$bid]);
                    if($auto_subscription_book){
                        $msg = '本书已开启自动订阅，请勿重复设置！';
                    }else{
                        BookAutoSubscription::create([
                            'uid'       => $this->uid,
                            'book_id'   => $bid
                        ]);
                        $status = 1;
                        $msg    = '本书自动订阅设置已开启！';
                    }
                }
            }else{
                $auto_subscription_book = BookAutoSubscription::get(['uid'=>$this->uid, 'book_id'=>$bid]);
                if($auto_subscription_book){
                    $auto_subscription_book->delete();
                }
                $msg = '本书自动订阅设置已取消！';
            }
        }
        
        return json(['status'=>$status,'msg'=>$msg]);
    }
}